<template>
    <div class="content-wrapper-view">
		<div class="content-wrapper-body"><!-- 开始 -->
			<!-- 工具栏- -->
	        <div class="filter-wrapper">
	            <el-form ref="filterForm" :model="listQuery" :inline="true">

                    <el-form-item size="medium">
                        <el-cascader
                            clearable
                            :options="categoryOptions"
                            :props="defaultProps"
                            v-model="categoryIds"
                            @change="handleChangeCascader"
                            placeholder="商品分类" 
                            style="width: 300px"
                            >
                        </el-cascader>
                    </el-form-item>

                    <el-form-item prop="brandId" size="medium">
                        <el-select v-model="listQuery.brandId" clearable placeholder="商品品牌" style="width: 100%">
                            <el-option
                                    v-for="item in brandOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="typeId" size="medium">
                        <el-select v-model="listQuery.typeId" clearable placeholder="商品类型" style="width: 100%">
                            <el-option
                                    v-for="item in typeOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    

	                <el-form-item prop="name" size="medium">
	                    <el-input v-model="listQuery.name" placeholder="商品名称"></el-input>
	                </el-form-item>
	
	                <el-form-item prop="status" size="medium">
	                    <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 100px">
	                        <el-option
	                                v-for="item in statusOptions"
	                                :key="item.value"
	                                :label="item.label"
	                                :value="item.value">
	                        </el-option>
	                    </el-select>
	                </el-form-item>
	
	                <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
	                <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
	                <el-button v-if="authorize('system:mallgoods:add')" type="primary" size="medium" icon="el-icon-plus" @click="handleCreate">添加</el-button>
	                <el-button v-if="authorize('system:mallgoods:delete')" type="danger" size="medium" icon="el-icon-delete" @click="handleDelete">批量删除</el-button>
	            </el-form>
	        </div>
	
			<!-- 表格 -->
	        <el-table
	                :data="list"
	                border fit
	                highlight-current-row
	                v-loading="listLoading"
	                element-loading-text="给我一点时间"
	                empty-text="-"
	                @selection-change="handleSelectionChange">
	
	            <el-table-column type="selection" width="55" align="center"></el-table-column>
				
                <el-table-column label="封面图" align="center">
                    <template slot-scope="scope">
                        <img @click="previewImg(scope.row.pictureUrl)" v-if="scope.row.pictureUrl" :src="scope.row.pictureUrl" alt="" style="width: 66px; height: 66px;cursor: pointer;">
                    </template>
	            </el-table-column>
				<el-table-column label="商品标题" align="center" width="300" :show-overflow-tooltip="true">
	                <template slot-scope="scope"> {{ scope.row.name }} </template>
	            </el-table-column>
				<el-table-column label="商品价格" align="center">
	                <template slot-scope="scope"> 
                        <el-tag type="primary">￥ {{ scope.row.price }}</el-tag> 
                    </template>
	            </el-table-column>
				<el-table-column label="库存量" align="center">
	                <template slot-scope="scope"> {{ scope.row.stock }} </template>
	            </el-table-column>
				<el-table-column label="库存警告" align="center">
	                <template slot-scope="scope"> {{ scope.row.warningStock }} </template>
	            </el-table-column>
				<el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        <el-tag type="info" v-if="scope.row.status === -1">下架</el-tag>
                        <el-tag type="success" v-if="scope.row.status === 1">上架</el-tag>
                        <el-tag type="primary" v-if="scope.row.status === 2">预售</el-tag>
                        <el-tag type="danger" v-if="scope.row.status === 0">未上架</el-tag>
                    </template>
	            </el-table-column>
				<el-table-column label="审核状态" align="center">
	                <template slot-scope="scope"> {{ scope.row.state }} </template>
                    <template slot-scope="scope">
                        <el-tag type="info" v-if="scope.row.state === '-1'">审核失败</el-tag>
                        <el-tag type="danger" v-if="scope.row.state === '0'">未审核</el-tag>
                        <el-tag type="success" v-if="scope.row.state === '1'">审核成功</el-tag>
                    </template>
	            </el-table-column>
				<el-table-column label="排序" align="center">
	                <template slot-scope="scope"> {{ scope.row.sort }} </template>
	            </el-table-column>
				<el-table-column label="创建时间" align="center" width="160">
	                <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}} </template>
	            </el-table-column>
				<el-table-column label="最后更新时间" align="center" width="160">
	                <template slot-scope="scope"> {{scope.row.utime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}} </template>
	            </el-table-column>
	            <el-table-column label="操作" width="180px" align="center">
	                <template slot-scope="scope">
	                    <el-button v-if="authorize('mallgoods:update')" size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>
	                    <el-button v-if="authorize('mallgoods:delete')" size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
	                </template>
	            </el-table-column>
	        </el-table>
	
			<!-- 分页工具栏 -->
	        <div v-if="!listLoading" class="pagination-container">
	            <el-pagination
	                    @size-change="handleSizeChange"
	                    @current-change="handleCurrentChange"
	                    :current-page="listQuery.page"
	                    :page-sizes="[10, 20, 30, 50]"
	                    :page-size="listQuery.limit"
	                    layout="total, sizes, prev, pager, next, jumper"
	                    :total="total">
	            </el-pagination>
	        </div>

            <!-- 商品图片预览窗口 -->
	        <el-dialog :visible.sync="dialogPreviewVisible">
	            <div class="preview">
                    <a :href="previewImgUrl" target="_blank"><img :src="previewImgUrl" alt="商品图片"></a>
                </div>
	        </el-dialog>
		
		</div>    	
		<back-to-top></back-to-top>
    </div>
</template>

<script>
    import { created, updated, deleted, selectOne, selectList, selectPage } from '@/api/mall/Goods'
    import { selectTree } from '@/api/mall/GoodsCategory'
    import { selectList as selectListBrand } from '@/api/mall/GoodsBrand'
    import { selectList as selectListType } from '@/api/mall/GoodsType'
    import { ResultMessage } from '@/libs/response'
    import { isAuth } from "@/libs/auth";
    import BackToTop from "@/components/BackToTop/index";
    import valid from '@/libs/rules'

    const statusOptions = [{ value: 0, label: '未上架' }, { value: -1, label: '下架' }, { value: 1, label: '上架' }, { value: 2, label: '预售' }]

    export default {
        name: 'MallGoods',
        components: {BackToTop},
        data() {
            let required = valid.required()
            return {
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 10,
                    name: null,
                    status: null,
                    categoryId: null,
                    brandId: null,
                    typeId: null
                },
                form: {
                    categoryId: null,
                    categoryIds: null,
                    sort: 99
                },
                rules: {
                    example: [required]
                },
                multipleSelection: [],
                statusOptions,
                categoryIds: [],
                categoryOptions: [],
                defaultProps: {
                    label: "name",
                    value: "id",
                    children: "children"
                },
                brandOptions: [],
                typeOptions: [],

                dialogPreviewVisible: false,
                previewImgUrl: null

            }
        },
        created() {
            this.getGoodsCategory()
            this.getGoodsBrand()
            this.getGoodsType()
            this.getPage()
        },
        methods: {
        	authorize(auth) {
				return isAuth(auth) //按钮权限验证
            },
            handleFilter() {//条件过滤
                this.listQuery.page = 1
                this.getPage()
            },
            handleResetFilter() {//重置过滤条件
                this.listQuery.categoryId = null
                this.categoryIds = []
                this.cancel('filterForm')
                this.getPage()
            },
            handleDialogClose() {//关闭窗口回调函数
                this.cancel('form')
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.page = 1
                this.listQuery.limit = val
                this.getPage()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getPage()
            },
            handleCreate() {
                this.$router.push({path: 'addGoods'})
            },
            handleUpdate(row) {//修改数据窗口
                this.$router.push({path: 'addGoods', query: {goodsId: row.id}})
            },
            handleDelete(row) {//批量删除数据
                let ids = []
                if (row.id != undefined) {
                    ids.push(row.id)
                } else {
                    if (this.multipleSelection.length > 0) {
                        for (let item of this.multipleSelection) {
                            ids.push(item.id)
                        }
                    }
                }
                if (ids.length <= 0) {
                    this.$notify({
                        title: '提示', message: '请选择需要删除的记录',
                        type: 'warning', duration: 2000
                    })
                } else {
                    this.$confirm('确定要删除？', '提示', {
                        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
                    }).then(() => {
                       deleted({idList: ids}).then(response => {
                            if(ResultMessage(response)) {
                                this.getPage()
                            }
                        }).catch(error => {
                            this.$notify({
                                title: '提示', message: '删除失败',
                                type: 'error', duration: 2000
                            })
                        })
                    }).catch(() => {})
                }
            },
            getData(id) { //根据ID查询数据
                this.listLoading = true
                return selectOne(id).then(response => {
                    if(ResultMessage(response, false)) {
                        this.listLoading = false
                        return response
                    } else {
                        this.listLoading = false
                        return null
                    }

                }).catch(error => {
                    this.$notify({
                        title: '提示', message: '根据ID获取数据失败',
                        type: 'error', duration: 2000
                    })
                    this.listLoading = false
                })
            },
            getPage() {//查询分页列表
                this.listLoading = true
                selectPage(this.listQuery).then(response => {
                    if(ResultMessage(response, false)) {
                        this.list = response.data.data.list
                        this.total = parseInt(response.data.data.total)
                        this.listLoading = false
                    } else {
                        this.listLoading = false
                    }
                }).catch(error => {
                    this.listLoading = false
                    this.$notify({
                        title: '提示', message: '查询列表失败',
                        type: 'error', duration: 2000
                    })
                })
            },
            create(formName) {//添加数据
                const set = this.$refs
                set[formName].validate((valid) => {
                    if (valid) {
                        created(this.form).then(response => {
                        	if(ResultMessage(response)) {
                                this.handleResetFilter()
                            } else {
                                this.dialogFormVisible = false
                            }
                        }).catch(error => {
                            this.$notify({
                                title: '提示', message: '添加失败',
                                type: 'error', duration: 2000
                            })
                        })
                    }
                })
            },
            update(formName) {//修改数据
                const set = this.$refs
                set[formName].validate((valid) => {
                    if (valid) {
                        updated(this.form).then(response => {
                            if(ResultMessage(response)) {
                                this.getPage()
                            }
                            this.dialogFormVisible = false
                        }).catch(error => {
                            this.$notify({
                                title: '提示', message: '修改失败',
                                type: 'error', duration: 2000
                            })
                        })
                    }
                })
            },
            cancel(formName) {
                this.dialogFormVisible = false
                const set = this.$refs
                set[formName].resetFields()
                this.form = {
                    sex: 1,
                    status: true
                }
            },

            previewImg(url) {
                this.dialogPreviewVisible = true
                this.previewImgUrl = url
            },

            /* 获取商品分类 */
            getGoodsCategory() {
                selectTree().then((response) => {
                    this.categoryOptions = response.data.data
                })
            },
            handleChangeCascader(value) {
                if(value.length > 0) {
                    this.form.categoryId = value[value.length -1]
                    this.form.categoryIds = value.join(',')
                    this.listQuery.categoryId = value[value.length -1]
                } else {
                    this.form.categoryId = null
                    this.form.categoryIds = null
                    this.listQuery.categoryId = null
                }
                
            },

            /* 获取商品品牌 */
            getGoodsBrand() {
                selectListBrand().then((response) => {
                    this.brandOptions = response.data.data
                })
            },

            /* 获取商品类型 */
            getGoodsType() {
                selectListType().then((response) => {
                    this.typeOptions = response.data.data
                })
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .preview{
        display:flex;
        justify-content: center;
    }
</style>